package com.hyy.netty.c3;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;
import java.util.Random;

public class LineDecoderClient {
    public static void main(String[] args) throws InterruptedException {
        send();
        System.out.println("finish");
    }

    private static String getLine(char c ,int length){
        StringBuilder sb = new StringBuilder(length+2);
        for (int i = 0; i < length; i++) {
            sb.append(c);
        }
        sb.append("\n");
        System.out.println(sb);
        return sb.toString();
    }

    private static void send() {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            //1、启动类
            Bootstrap bootstrap = new Bootstrap()
                    //2、添加 EventLoop
                    .group(worker)
                    //3、选择客户端的channel的实现
                    .channel(NioSocketChannel.class)
                    //4、添加处理器
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override //在连接建立后被调用
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                            ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    ByteBuf buffer = ctx.alloc().buffer();
                                    char c = '0';
                                    Random r = new Random();
                                    for (int i = 0; i < 10; i++) {
                                        String l = getLine(c, r.nextInt(256) + 1);
                                         c++;
                                         buffer.writeBytes(l.getBytes());
                                    }
                                    ctx.writeAndFlush(buffer);

                                }
                            });

                        }
                    });
            //5、连接到服务器
            ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress("localhost", 8080)).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            worker.shutdownGracefully();
        }
    }
}
